<template>
  <div class="viewport" ref="viewportRef">
    <div class="container" ref="containerRef">
      <Chart ref="chartRef" :option="option"></Chart>
    </div>
  </div>
</template>

<script setup lang="ts">
import Chart from "@/components/charts/index.vue";
import { ChartInstance, ECOption } from "@/components/charts/index";
import { throttle } from "radash";

const option: ECOption = {
  title: { text: "ECharts 入门示例" },
  tooltip: { trigger: "axis" },
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: "line",
    },
  ],
};

const viewportRef = ref<HTMLDivElement>();
const containerRef = ref<HTMLDivElement>();
const chartRef = ref<InstanceType<typeof Chart>>();
let chartInstance: ChartInstance | null | undefined = null;

const resizeHandler = throttle({ interval: 300 }, () => {
  const viewportWidth = viewportRef.value!.clientWidth;
  const viewportHeight = viewportRef.value!.clientHeight;
  const designDraftWidth = 1920; //设计稿的宽度
  const designDraftHeight = 1080; //设计稿的高度
  const scale =
    viewportWidth / viewportHeight < designDraftWidth / designDraftHeight
      ? viewportWidth / designDraftWidth
      : viewportHeight / designDraftHeight;
  containerRef.value!.style.transform = `scale(${scale}) translate(-50%, -50%)`;
  chartInstance?.resize();
});

onMounted(() => {
  chartInstance = chartRef.value?.getChartInstance();
  resizeHandler();
  window.addEventListener("resize", resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeHandler);
});
</script>

<style lang="less" scoped>
.viewport {
  position: relative;
  height: 100%;

  /* width: 1920px;
  height: 1080px;
  background-color: lightblue;
  position: absolute;
  top: 50%;
  left: 50%; */
  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 1920px;
    height: 1080px;
    background-color: lightblue;
    transform-origin: 0 0;
    transform: translate(-50%, -50%);
  }
}
</style>
